<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学号" prop="studentNo">
        <el-input
          v-model="queryParams.studentNo"
          placeholder="请输入学号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="cellNo">
        <el-input
          v-model="queryParams.cellNo"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="校区" prop="campus">
          <treeselect style="width:200px" v-model="queryParams.campusId" :options="campusOptions" 
                :multiple="false" :disableBranchNodes="true"
                :select="selectOthers"
                :show-count="true" placeholder="请选择归属校区" />
      </el-form-item>
      <el-form-item label="班级" prop="classId">
        <el-select
              v-model="queryParams.classId"
              placeholder="请选班级"
              clearable
              size="small"
              style="width: 200px"
            >
              <el-option
                v-for="classInfo in classOptions"
                :key="classInfo.classId"
                :label="classInfo.className"
                :value="classInfo.classId"
              />
            </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:attendance:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="考勤ID" align="center" prop="attendId" />-->
      <el-table-column label="学号" align="center" prop="studentNo" />
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column label="电话" width="150px" align="center" prop="cellNo" />
      <el-table-column label="科目" align="center" prop="subjectName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="迟到次数" align="center" prop="lateNum" />
      <el-table-column label="早退次数" align="center" prop="leaveNum" />
      <el-table-column label="旷课次数" align="center" prop="truancyFlagNum" />
      <el-table-column label="请假次数" align="center" prop="leaveFlagNum" />
      <el-table-column label="操作" fixed="right" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleQryPunches(scope.row)"
            v-hasPermi="['edu:attendance:query']"
          >打卡信息</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleQryLeaves(scope.row)"
            v-hasPermi="['edu:attendance:query']"
          >请假信息</el-button> -->
          <router-link :to="'/stuAttendanceDetail/attendance/index/' + scope.row.studentId" class="link-type">
            <span>考勤信息</span>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生考勤信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeName" @tab-click="handleTabChange">
          <el-tab-pane label="基本信息" name="first">
          <el-form-item label="学生" prop="studentName">
            <el-input v-model="form.studentName" placeholder="请输入学生" />
          </el-form-item>
          <!--
          <el-form-item label="课表详情ID" prop="scheduleInfoId">
            <el-input v-model="form.scheduleInfoId" placeholder="请输入课表详情ID" />
          </el-form-item>
          -->
          <el-form-item label="迟到时间" prop="lateTime">
            <el-date-picker clearable size="small" style="width: 200px"
              v-model="form.lateTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择早退时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="早退时间" prop="leaveTime">
            <el-date-picker clearable size="small" style="width: 200px"
              v-model="form.leaveTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择早退时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="是否旷课" prop="truancyFlag">
            <el-select v-model="form.truancyFlag" placeholder="请选择是否旷课" clearable size="small">
              <el-option
                    v-for="dict in truancyFlagOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
            </el-select>
          </el-form-item>
          <el-form-item label="是否请假" prop="leaveFlag">
            <el-select v-model="form.leaveFlag" placeholder="请选择是否请假" clearable size="small">
              <el-option
                    v-for="dict in leaveFlagOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
            </el-select>
          </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="打卡信息" name="second">
            <el-form-item label="时间">
              <el-date-picker
                  v-model="dateRange"
                  size="small"
                  style="width: 240px"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              <el-button size="mini" type="primary" @click="handelPunchesQry">查 询</el-button>
            </el-form-item>
            <el-table v-loading="loading" :data="studentPunchsList" >
              <el-table-column label="打卡时间" align="center" prop="punchTime">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.punchTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttendance, getAttendance, delAttendance, addAttendance, updateAttendance, exportAttendance, listStudentAttendance } from "@/api/edu/attendance";
import { listPunchsByAttendance  } from "@/api/edu/studentPunchs";
import { treeselectByType } from "@/api/system/dept";
import { ajaxList } from "@/api/edu/classInfo";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Attendance",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生考勤信息表格数据
      attendanceList: [],
      campusOptions: [],
      classOptions: [],
      truancyFlagOptions: [],
      leaveFlagOptions: [],
      activeName: "first",
      studentPunchsList: [],
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        studentNo: null,
        studentName: null,
        cellNo: null,
        campusId: null,
        classId: null,
        truancyFlag: null,
        leaveFlag: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        studentId: [
          { required: true, message: "学生ID不能为空", trigger: "blur" }
        ],
        scheduleInfoId: [
          { required: true, message: "课表详情ID不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    const studentId = this.$route.params && this.$route.params.studentId;
    this.queryParams.studentId = studentId
    this.getList();
    this.defaultDate()
    this.queryCampus()
    this.getDicts("edu_truancy_flag").then(response => {
      this.truancyFlagOptions = response.data;
    });
    this.getDicts("edu_leave_early_flag").then(response => {
      this.leaveFlagOptions = response.data;
    });
  },
  watch: {
    'queryParams.campusId': 'selectOthers'
  },
  methods: {
    queryCampus() {
      // 查询校区（deptType = 1）
      treeselectByType("1").then(response => {
        this.campusOptions = response.data;
      })
    },
    selectOthers() {
      this.queryClassInfo();
    },
    queryClassInfo() {
      if(this.queryParams.campusId === undefined || this.queryParams.campusId === null) {
        this.$message({
            type: 'warning',
            message: '请选择校区'
          })
          return
      }
      let classInfo = {
        campusId : this.queryParams.campusId
      }
      ajaxList(classInfo).then(response => {
        this.classOptions = response.data
      })
    },
    truancyFlagFormat(row, column) {
      return this.selectDictLabel(this.truancyFlagOptions, row.truancyFlag);
    },
    leaveFlagFormat(row, column) {
      return this.selectDictLabel(this.leaveFlagOptions, row.leaveFlag);
    },
    //设置默认日期
    defaultDate(){
        //获取新的时间(2019.4.12）
        let date = new Date()
        //获取当前时间的年份转为字符串
        let year = date.getFullYear().toString()   //'2019'
        //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
        let month = date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1).toString():(date.getMonth()+1).toString()  //'04'
        //获取天，判断是否小于10，如果是在字符串前面拼接'0'
        let da = date.getDate() < 10 ? '0'+date.getDate().toString():date.getDate().toString()  //'12'
        //字符串拼接，开始时间，结束时间
        let end = year + '-' + month + '-' + da  //当天'2019-04-12'
        let beg = year + '-' + month + '-01'    //当月第一天'2019-04-01'
        this.dateRange = [beg,end] //将值设置给插件绑定的数据
    },
    /** 查询学生考勤信息列表 */
    getList() {
      this.loading = true;
      listStudentAttendance(this.queryParams).then(response => {
        this.attendanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        attendId: null,
        studentId: null,
        scheduleInfoId: null,
        lateTime: null,
        leaveTime: null,
        truancyFlag: null,
        leaveFlag: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.attendId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生考勤信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const attendId = row.attendId || this.ids
      getAttendance(attendId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生考勤信息";
      });
    },
    handleQryPunches(row) {
      this.reset();
      const attendId = row.attendId || this.ids
      getAttendance(attendId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查询学生考勤信息";
        this.activeName = "second"
        this.handleTabChange()
      });
      
    },
    handleQryLeaves(row) {
      // TODO 
      console.log(JSON.stringify())
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.attendId != null) {
            updateAttendance(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttendance(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const attendIds = row.attendId || this.ids;
      this.$confirm('是否确认删除学生考勤信息编号为"' + attendIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAttendance(attendIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有学生考勤信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportAttendance(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleTabChange() {
      if("second" === this.activeName) {
        // 查一个月时间范围
        listPunchsByAttendance(this.form.studentId, this.dateRange).then(response => {
            this.studentPunchsList = response.data
            //console.log(JSON.stringify(this.studentPunchsList))
          })
        
      }
    },
    handelPunchesQry() {
      this.activeName = "second"
      this.handleTabChange()
    }
  }
};
</script>
